from fastapi import APIRouter, Header
from starlette.requests import Request

from config import ROUTER_PREFIX
from model.db.mapper.users_mapper import email_is_exist, get_user_by_username_null, get_user_by_email_null
from model.params.users_params import Email
from model.redis.utils import redis_save_emailcode
from util import img_util, success_res, SuccessCode, get_email_code, error_res, ErrorCode
from util.access_token import parse_token
code_router = APIRouter(prefix="/code", tags=['验证码获取'])


@code_router.get("/login", name="登录时获取验证码")
async def get_code(request: Request):
    ip = request.scope["client"][0]
    verify, image = img_util.create_code()
    path = img_util.save_code(ip, verify, image)
    return success_res({
        "path": ROUTER_PREFIX + "/" + path,
    }, SuccessCode.GET)


@code_router.get("/email/register", name="发送邮箱验证码(注册时使用)")
async def send_email_code(email: str, request: Request):
    user = get_user_by_email_null(email)
    if user is not None:
        return error_res(ErrorCode.EMAIL_ISEXIST)
    email_code = get_email_code(email)
    access_token = await redis_save_emailcode(request, email, email_code)
    if access_token is None:
        return error_res(ErrorCode.EMAIL_CODE_NOTOK,"验证码发送失败")
    else:
        return success_res("发送成功，验证码在五分钟内有效", SuccessCode.EMAILCODE_SEND)


@code_router.post("/email/password", name="发送邮箱验证码(找回密码时使用)")
async def send_email_code(param: Email, request: Request):
    user = get_user_by_email_null(param.email)
    if user is None:
        return error_res(ErrorCode.EMAIL_NOT_EXIST)
    email_code = get_email_code(param.email)
    access_token = await redis_save_emailcode(request, param.email, email_code)
    if access_token is None:
        return error_res("验证码发送失败", SuccessCode.Error)
    else:
        return success_res("发送成功，验证码在一分钟内有效", SuccessCode.EMAILCODE_SEND)
